import random
from time import sleep

from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver import ActionChains


# 登录
def login(driver, user, data):
    print("开始登录")
    # 输入用户名
    select(driver, data[1]).send_keys(user["user"])
    # 输入密码
    select(driver, data[2]).send_keys(user["passwd"])
    # 点击登录
    select(driver, data[3]).click()


# 登出
def logout(driver, data):
    select(driver, data[4]).click()
    print("退出登录")


# 验证码
def verificationCode(driver, data):
    print("验证码")
    # 定位滑块
    try:
        div = select(driver, data[5])
    except NoSuchElementException as e:
        div = select(driver, data[6])

    # 开始滑动滑块
    ActionChains(driver).click_and_hold(on_element=div).perform()
    sleep(0.15)
    ActionChains(driver).move_to_element_with_offset(to_element=div, xoffset=random.randint(100, 125),
                                                     yoffset=random.randint(0, 10)).perform()
    sleep(0.4)
    ActionChains(driver).move_to_element_with_offset(to_element=div, xoffset=random.randint(125, 150),
                                                     yoffset=random.randint(10, 20)).perform()
    sleep(0.2)
    ActionChains(driver).move_to_element_with_offset(to_element=div, xoffset=random.randint(150, 160),
                                                     yoffset=random.randint(20, 35)).release().perform()


# 以下为模块测试代码
if __name__ == '__main__':
    print('test_login')
    from selenium import webdriver
    import readcsv as Csv
    import readjson as Json
    from selector import select
    from login import login, verificationCode, logout

    # 读取csv文件
    user = Json.read("../config/user.json")
    add_user = Csv.read("../config/adduser.csv")
    data = Csv.read("../config/data.csv")
    # 避免webdriver检测
    options = webdriver.ChromeOptions()
    options.add_argument('--disable-blink-features=AutomationControlled')
    options.add_experimental_option('excludeSwitches', ['enable-automation'])
    driver = webdriver.Chrome(options=options)
    # 设置隐式等待为10秒
    driver.implicitly_wait(5)
    print("开始")
    # 打开12306网站
    driver.get("https://www.12306.cn/")
    # 设置浏览器全屏
    driver.maximize_window()
    # 点击登录
    select(driver, data[0]).click()
    # 登录模块
    login(driver, user, data)
    # 验证码
    verificationCode(driver, data)
    # 点击疫情确认按钮
    select(driver, data[7]).click()
    # 登出
    logout(driver, data)
    # 退出浏览器
    driver.quit()
    print("关闭浏览器")
else:
    try:
        from tools.selector import select
    except Exception:
        from selector import select
